package uit.nfcmenu.activity;


import java.util.ArrayList;
import java.util.Locale;

import uit.nfcmenu.R;
import uit.nfcmenu.db.model.IDataChangeHandler;
import uit.nfcmenu.db.model.ItemModel;
import uit.nfcmenu.db.model.OrderModel;
import uit.nfcmenu.manager.OrderManager;
import uit.nfcmenu.manager.WaiterGlobalObject;
import uit.nfcmenu.util.AnimationHelper;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.util.ImageHelper;
import uit.nfcmenu.util.UiUtilities;
import uit.nfcmenu.webservice.JSONParser;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.PreferenceHelper;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class WaiterDetailActivity extends BaseActivity 
		implements OnClickListener, IDataChangeHandler, OnTouchListener {
	String tag = WaiterDetailActivity.class.getSimpleName();
	
	private TextView tvDiscount, tvPrice, tvDescription, tvName;
	private EditText txtQuantity, txtTable, txtComment;
	private Button btnOrder;
	private ImageView img;
	private ViewFlipper vf;
	private float oldTouchValue;

	private Button[] arrBtnFlags = new Button[3];
	private String mLanguage;
	
//	OrderModel mOrder;
//	ItemModel item;
	ArrayList<ItemModel> mModels;
	private int mIndex = 0;
	

	// values for view
//	int cornerRadius = 0;
	int width = 0;
	int height = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		
		changeLanguage(null);
		initView();
		initData();		
		initListener();
	}

	@Override
	protected Context getActivityContext() {
		return this;
	}
	
	@Override
	protected void initView() {
		super.initView();
		tvName = (TextView) findViewById(R.id.tvStuffName);
		tvDescription = (TextView) findViewById(R.id.tvDescriptionContent);
		tvDiscount = (TextView) findViewById(R.id.tvDiscount);
		tvPrice = (TextView) findViewById(R.id.tvPrice);
		
		txtQuantity = (EditText) findViewById(R.id.txtQuantity);
		txtTable = (EditText) findViewById(R.id.txtTable);
		txtComment = (EditText) findViewById(R.id.txtNote);
		
		arrBtnFlags[CommConstant.LANGUAGE_EN_INDEX] = (Button) findViewById(R.id.btnFlagEn);
		arrBtnFlags[CommConstant.LANGUAGE_JA_INDEX] = (Button) findViewById(R.id.btnFlagJa);
		arrBtnFlags[CommConstant.LANGUAGE_VI_INDEX] = (Button) findViewById(R.id.btnFlagVi);
		
		btnOrder = (Button) findViewById(R.id.btnOrder);
		
		img = (ImageView) findViewById(R.id.img_goods);
		vf = (ViewFlipper) findViewById(R.id.flipperDetail);
		
		ScrollView sView = (ScrollView) findViewById(R.id.scrollbar);
		sView.setVerticalScrollBarEnabled(false);
        sView.setHorizontalScrollBarEnabled(false);

		// assign values for view
//		Display display = getWindowManager().getDefaultDisplay();
//		cornerRadius = (int) mRes.getDimension(R.dimen.corner_radius);
		width = (int) (mRes.getDimension(R.dimen.detail_image_width_large)) ;
		height = (int) mRes.getDimension(R.dimen.detail_image_height);
	}

	protected void initData() {		
		mModels = WaiterGlobalObject.arrItems;
		Bundle bundle = getIntent().getExtras();
		int index = bundle.getInt("itemIdex");
		ItemModel item = mModels.get(index);
		if (item != null) {
			mIndex = index;
			updateDetailView(mIndex);
		}
        updateItemInfoByLanguage(mIndex, PreferenceHelper.loadLanguage(mContext));
	}

	protected void initListener() {
		btnOrder.setOnClickListener(this);
		
		arrBtnFlags[CommConstant.LANGUAGE_EN_INDEX].setOnClickListener(this);
		arrBtnFlags[CommConstant.LANGUAGE_JA_INDEX].setOnClickListener(this);
		arrBtnFlags[CommConstant.LANGUAGE_VI_INDEX].setOnClickListener(this);
		
		img.setOnTouchListener(this);
	}

	protected void changeLanguage(String language) {
		if (language == null) {
			// use default
			mLanguage = PreferenceHelper.loadLanguage(mContext);
		} else {
			mLanguage = language;
		}
		
		// change server text
		updateItemInfoByLanguage(mIndex, mLanguage);
	}

	private void updateDetailView(int index) {
		ItemModel model = mModels.get(index);
		
		// show image in ImageView obj
		ImageHelper.setViewWithRoundCorners(img, 
				model.getBitmap(), width, height, 0);
					
		updateItemInfoByLanguage(index, mLanguage);
	}
	
	private void updateItemInfoByLanguage(int index, String language) {
		if (tvName != null && mModels != null) { // mean init view done
			ItemModel item = mModels.get(index);
			tvName.setText(JSONParser.getStringByLanguage(item.getName(), language));
			tvDescription.setText(JSONParser.getStringByLanguage(item.getDescription(), language));
			int price = (int)item.getPrice();
			int disc = (int)item.getDiscount();
			if (disc == 0 || disc == price) {
				tvPrice.setVisibility(View.GONE);
				tvDiscount.setText("$"+price);
			} else {
				tvPrice.setVisibility(View.VISIBLE);
				tvPrice.setText("$"+price);
				tvDiscount.setText("$"+disc);
			}
			
			// set focus for flags
			int languageIndex = CommConstant.getLanguageIndex(language);
			for (int i = 0; i < arrBtnFlags.length; i++) {
				arrBtnFlags[i].setSelected(i == languageIndex);
			}
		}
	}

	@Override
	public void onClick(View v) {
		UiUtilities.hideKeyboard(mContext, v);
		switch (v.getId()) {
		case R.id.btnOrderList:
			launchOrderListActivity();
			break;
		case R.id.btnLogout:
			new DoLogout().execute();
			break;
		case R.id.btnMenu:
			launchMenuActivity();
			break;
		case R.id.btnOrder:
			// TODO post order
			try { // try catch for checking input table & quantity
				final int table = Integer.parseInt(txtTable.getText().toString());
				final int quantity = Integer.parseInt(txtQuantity.getText().toString());
				final String comment = txtComment.getText().toString();
				doIfMeetNetworkOrShowFailStatus(mContext, BaseActivity.SHOW_MESSAGE_ON_DIALOG, 
						new Runnable() { @Override public void run() {
							requestToOrder(mContext, mModels.get(mIndex).getId(), 
									table, quantity, comment);
							finish();
						}});
			} catch (Exception e) {
				Log.e(tag, "Post order Exception : info: "
						+"table="+txtTable.getText().toString()+", "
						+"quantity="+txtQuantity.getText().toString()+", "
						+txtComment.getText().toString()
						, e);
				UiUtilities.popupAlertMessage(mContext, R.string.message, 
						R.string.mess_require_quantity_number, R.string.ok);
			}
			break;
		case R.id.btnFlagEn:
			updateItemInfoByLanguage(mIndex, Locale.ENGLISH.getLanguage().toString());
			break;
		case R.id.btnFlagJa:
			updateItemInfoByLanguage(mIndex, Locale.JAPANESE.getLanguage().toString());
			break;
		case R.id.btnFlagVi:
			updateItemInfoByLanguage(mIndex, CommConstant.LANGUAGE_VI);
			break;
		default:
		}
	}

	private void requestToOrder(Context context, 
			int itemId, int table, int quantity, String comment) {
		OrderModel order = new OrderModel();
		order.setItemID(itemId);
		order.setStatus(CommConstant.mOrderStatus[CommConstant.STATUS_NEW]);
		order.setQuantity(quantity);
		order.setTableNo(table);
		order.setComment(comment);
		try {
			OrderManager.getInstance(mContext).postOrders(order);
		} catch (MyException e) {
			e.printStackTrace();
		}
	}

	public void onDataChanged() { }

	@Override
	public Context getContext() {
		return getBaseContext();
	}
	
//	@Override
//	public boolean onTouchEvent(MotionEvent touchevent) {
//		switch (touchevent.getAction()) {
//		case MotionEvent.ACTION_DOWN: {
//			Log.i("move", "ACTION_DOWN");
//			oldTouchValue = touchevent.getX();
//			break;
//		}
////		case MotionEvent.ACTION_MOVE: {
////			Log.i("move", "ACTION_MOVE");
////			break;
////		}
//		case MotionEvent.ACTION_UP: {
//			Log.i("move", "ACTION_UP");
//			float currentX = touchevent.getX();
//			int n = mModels.size();
//			
//			if (oldTouchValue < currentX && (currentX - oldTouchValue) > 20) {
//				mIndex = (mIndex < n - 1) ? (mIndex + 1) : 0;
//				updateDetailView(mIndex);
//				
//				vf.setInAnimation(AnimationHelper.inFromLeftAnimation());
//				vf.setOutAnimation(AnimationHelper.outToRightAnimation());
//				vf.showNext();
//			}
//			
//			if (oldTouchValue > currentX && (oldTouchValue - currentX) > 20) {
//				mIndex = ((mIndex - 1) >= 0) ? (mIndex - 1) : (n - 1);
//				updateDetailView(mIndex);
//				
//				vf.setInAnimation(AnimationHelper.inFromRightAnimation());
//				vf.setOutAnimation(AnimationHelper.outToLeftAnimation());
//				vf.showPrevious();
//			}
//			
//			break;
//		}
//		}
//		return true;
//	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			Log.i("move", "ACTION_DOWN");
			oldTouchValue = event.getX();
			break;
		}
//		case MotionEvent.ACTION_MOVE: {
//			Log.i("move", "ACTION_MOVE");
//			break;
//		}
		case MotionEvent.ACTION_UP: {
			Log.i("move", "ACTION_UP");
			float currentX = event.getX();
			int n = mModels.size();
			
			if (oldTouchValue < currentX && (currentX - oldTouchValue) > 20) {
				mIndex = (mIndex < n - 1) ? (mIndex + 1) : 0;
				updateDetailView(mIndex);
				
				vf.setInAnimation(AnimationHelper.inFromLeftAnimation());
				vf.setOutAnimation(AnimationHelper.outToRightAnimation());
				vf.showNext();
			}
			
			if (oldTouchValue > currentX && (oldTouchValue - currentX) > 20) {
				mIndex = ((mIndex - 1) >= 0) ? (mIndex - 1) : (n - 1);
				updateDetailView(mIndex);
				
				vf.setInAnimation(AnimationHelper.inFromRightAnimation());
				vf.setOutAnimation(AnimationHelper.outToLeftAnimation());
				vf.showPrevious();
			}
			
			break;
		}
		}
		return true;
	}
}
